package com.app.service.impl;

import com.app.mapper.*;
import com.app.model.*;
import com.app.service.*;
import com.app.utils.CommonHelp;
import com.app.vo.VerificationRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.List;

/**
 * <p>
 * 商家核销记录表 服务实现类
 * </p>
 *
 * @author 16693103420
 * @since 2024-01-31
 */
@Service
public class VerificationRecordServiceImpl extends ServiceImpl<VerificationRecordMapper, VerificationRecordModel> implements VerificationRecordService {
    @Autowired
    private VerificationRecordMapper verificationRecordMapper;
    @Autowired
    private VerificationRecordService verificationRecordService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private InviteConfigMapper inviteConfigMapper;
    @Autowired
    private InviteRecordMapper inviteRecordMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private IntegralRecordMapper integralRecordMapper;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private VoucherRecordMapper voucherRecordMapper;
    @Autowired
    private MessageBoxMapper messageBoxMapper;
    @Autowired
    private IDividedIntoRecordService dividedIntoRecordService;

    @Autowired
    private AdminUserService adminUserService;


    @Override
    public VerificationRecordVo getVerificationRecordList(Integer page, Integer limit, Integer businessId) {
        Page<VerificationRecordModel> page1 = new Page<>(page, limit);
        QueryWrapper<VerificationRecordModel> qw = new QueryWrapper<>();
        if (businessId != null) {
            qw.eq("business_id", businessId);
        }
        qw.orderByDesc("create_time");
        Page<VerificationRecordModel> verificationRecordPage = verificationRecordMapper.selectPage(page1, qw);
        List<VerificationRecordModel> verificationRecordList = verificationRecordPage.getRecords();

        long count = verificationRecordPage.getTotal();
        VerificationRecordVo VerificationRecordVo = new VerificationRecordVo();
        VerificationRecordVo.setList(verificationRecordList);
        VerificationRecordVo.setCount((int) count);
        return VerificationRecordVo;
    }

    @Override
    public String businessVerification(String orderId, UserModel userModel) {
        //判断订单是否有效
        QueryWrapper<OrderModel> qw = new QueryWrapper<>();
        qw.eq("order_id", orderId);
        OrderModel order = orderService.getOne(qw);
        if (order == null) {
            return "该订单不存在";
        }
        BusinessModel businessModel = businessService.getById(order.getBusinessId());
        if (businessModel == null) {
            return "该商家不存在";
        } else {
            if (businessModel.getBusinessStatus() == 2) {
                return "该商家暂未营业";
            }
            if (!userModel.getPhone().equals(businessModel.getUserPhone())) {
                return "请使用该订单商家进行核销";
            }
        }
        if (order.getStatus() != 1) {
            return "此订单已核销";
        }
        //获取积分规则
        List<InviteConfigModel> inviteConfigModels = inviteConfigMapper.selectList(null);
        //新增核销记录
        VerificationRecordModel verificationRecord = new VerificationRecordModel();
        verificationRecord.setBusinessId(order.getBusinessId());
        verificationRecord.setActivityName(order.getActivityName());
        verificationRecord.setOrderId(order.getOrderId());
        verificationRecord.setUserId(order.getUserId());
        verificationRecord.setPayAmount(BigDecimal.valueOf(order.getVoucher()));
        Double contributeIntegral = order.getVoucher() * inviteConfigModels.get(0).getBrokerageTwo();
        DecimalFormat df = new DecimalFormat("#.##");
        df.setRoundingMode(RoundingMode.HALF_UP); // 设置四舍五入模式
        String formattedContributeIntegral = df.format(contributeIntegral);
        //贡献积分,当前核销订单价值*当前配置比例
        verificationRecord.setContributeIntegral(Double.parseDouble(formattedContributeIntegral));
        verificationRecord.setCreateTime(CommonHelp.getNowTimestamp());
        verificationRecord.setOrderId(orderId);
        verificationRecordService.save(verificationRecord);
        //参与分成的券/手续费
        Double dividedIntoCoupons = order.getVoucher() * inviteConfigModels.get(0).getTransactionFeeRatio();
        //抽成实际到账
        BigDecimal newTransferAmount = BigDecimal.valueOf(order.getVoucher()).subtract(BigDecimal.valueOf(dividedIntoCoupons));
        //核销成功后将益联券给商家用户
        userModel.setVoucher(userModel.getVoucher() + newTransferAmount.doubleValue());
        userService.updateById(userModel);
        //增加益联券记录
        VoucherRecordModel voucherRecordModel = new VoucherRecordModel();
        voucherRecordModel.setName("核销成功");
        voucherRecordModel.setTypeName("核销");
        String amountVoucher = "+" + newTransferAmount + "券";
        voucherRecordModel.setVoucher(amountVoucher);
        voucherRecordModel.setUserId(userModel.getId());
        voucherRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
        voucherRecordModel.setVoucherType(1);
        voucherRecordModel.setVoucherAmount(order.getVoucher());
        voucherRecordModel.setWriteOff(1);
        voucherRecordMapper.insert(voucherRecordModel);

        QueryWrapper<VoucherRecordModel> voucherRecordModelQueryWrapper = new QueryWrapper<>();
        voucherRecordModelQueryWrapper.eq("type_name", "活动抢购");
        voucherRecordModelQueryWrapper.eq("user_id", userModel.getId());
        voucherRecordModelQueryWrapper.eq("order_id", orderId);
        voucherRecordModelQueryWrapper.eq("write_off", 2);
        voucherRecordModelQueryWrapper.last("limit 1");
        VoucherRecordModel model = this.voucherRecordMapper.selectOne(voucherRecordModelQueryWrapper);
        if (model != null)
        {
            model.setWriteOff(1);
            this.voucherRecordMapper.updateById(model);
        }
        //消息盒子记录数据
        MessageBoxModel messageBoxModel = new MessageBoxModel();
        messageBoxModel.setUserId(userModel.getId());
        messageBoxModel.setQuiltUserId(userModel.getId());
        messageBoxModel.setTypeName("核销通知");
        messageBoxModel.setVoucher(newTransferAmount.doubleValue());
        messageBoxModel.setNotes("【" + order.getActivityName() + "】 核销成功(扣除"+dividedIntoCoupons+"手续费)");
        messageBoxModel.setCreateTime(CommonHelp.getNowTimestamp());
        messageBoxModel.setOrderSn(orderId);
        messageBoxMapper.insert(messageBoxModel);
        //将用户贡献积分加到邀请人账户上
        //获取返佣比例
        Double brokerage = inviteConfigModels.get(0).getBrokerage();
        Double brokerageTwo = inviteConfigModels.get(0).getBrokerageTwo();
        //分佣积分
        Double voucher = order.getVoucher();//消费的券
        double v = voucher * inviteConfigModels.get(0).getConversion();//根据比例转换的积分
        double fist = v * brokerage;
        double second = v * brokerageTwo;
        //一级分佣
        UserModel user = userService.getById(order.getUserId());
        user.setIntegral(user.getIntegral() + fist);
        userService.updateById(user);
        //新增积分记录
        IntegralRecordModel integralRecordModel = new IntegralRecordModel();
        integralRecordModel.setName("活动抢购返还积分");
        integralRecordModel.setTypeName("返还积分");
        integralRecordModel.setContent("活动【" + order.getActivityName() + "】核销成功");
        String amountIntegral = String.format("+%.2f分", fist);
        integralRecordModel.setIntegral(amountIntegral);
        integralRecordModel.setUserId(user.getId());
        integralRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
        integralRecordModel.setVoucherType(1);
        integralRecordModel.setVoucherAmount(fist);
        integralRecordMapper.insert(integralRecordModel);
        QueryWrapper<InviteRecordModel> inviteRecordQW = new QueryWrapper<>();
        inviteRecordQW.eq("quilt_invite_id", user.getId());
        InviteRecordModel inviteRecordModel = inviteRecordMapper.selectOne(inviteRecordQW);
        if (inviteRecordModel != null && inviteRecordModel.getInviteId() != null) {
            UserModel inviteUser = userService.getById(inviteRecordModel.getInviteId());//此用户的邀请人对象
            if (inviteUser != null) {
                inviteUser.setIntegral(inviteUser.getIntegral() + second);
                userService.updateById(inviteUser);
                //新增积分记录
                IntegralRecordModel integralRecordModel1 = new IntegralRecordModel();
                integralRecordModel1.setName("粉丝贡献积分(活动抢购)");
                integralRecordModel1.setTypeName("贡献积分(活动抢购)");
                integralRecordModel1.setContent(user.getName() + "活动抢购");
                String amountIntegral1 = String.format("+%.2f分", second);
                integralRecordModel1.setIntegral(amountIntegral1);
                integralRecordModel1.setVoucherAmount(second);
                integralRecordModel1.setVoucherType(1);
                integralRecordModel1.setUserId(inviteUser.getId());
                integralRecordModel1.setCreateTime(CommonHelp.getNowTimestamp());
                integralRecordMapper.insert(integralRecordModel1);
            }
        }else{
            //给平台用户发放积分
            this.adminUserService.accumulatePointsForCurrentPlatformUser(order.getUserId(),"套餐核销上级分佣积分",BigDecimal.valueOf(second));
        }
        //将订单状态修改
        order.setStatus(2);
        order.setUpdateTime(CommonHelp.getNowTimestamp());
        orderService.updateById(order);
        //核销代理分成
        this.dividedIntoRecordService.dividingByRegionalAgent(user,userModel, BigDecimal.valueOf(dividedIntoCoupons), orderId, 2);
        return "核销成功";
    }
}
